package com.dsp.week07.aop;

import com.dsp.week07.conf.DataSourceTypeThreadLocal;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(dataSourceSelect)")
    public void changeDataSource(JoinPoint point, DataSourceSelect dataSourceSelect) throws Throwable {
        DataBaseType value = dataSourceSelect.value();
        if (DataBaseType.Primary.compareTo(value) == 0) {
            DataSourceTypeThreadLocal.setDataBaseType(DataBaseType.Primary);
            System.err.println("Primary业务");
        } else if (DataBaseType.Secondary.compareTo(value) == 0) {
            DataSourceTypeThreadLocal.setDataBaseType(DataBaseType.Secondary);
            System.err.println("Secondary业务");
        } else {
            //默认使用主数据库
            DataSourceTypeThreadLocal.setDataBaseType(DataBaseType.Primary);
            System.err.println("default Primary业务");
        }

    }

    @After("@annotation(dataSourceSelect)")
    public void restoreDataSource(JoinPoint point, DataSourceSelect dataSourceSelect) {
        DataSourceTypeThreadLocal.clearDataBaseType();
    }
}
